package com.fnd.med.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.ByteArrayOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class MeapsUtil
{
  public static Base64 base64 = new Base64();

  @SuppressWarnings("unchecked")
public static <T> T cope(T object)
  {
    ByteArrayOutputStream byteOut;
    try
    {
      byteOut = new ByteArrayOutputStream();
      ObjectOutputStream out = new ObjectOutputStream(byteOut);
      out.writeObject(object);
      ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
      byteOut.close();
      ObjectInputStream in = new ObjectInputStream(byteIn);
      return (T) in.readObject();
    } catch (Exception e) {
      throw new RuntimeException();
    }
  }

  public static String md5encode(String str)
  {
    MessageDigest md = null;
    try {
      md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return base64Encrypt(md.digest(str.getBytes()));
  }

  private static String base64Encrypt(byte[] b)
  {
    return base64.encodeToString(b);
  }

  public static byte[] base64Decrypt(String s)
  {
    return Base64.decodeBase64(s);
  }

  public static String getActivateCode()
  {
    String str = "0123456789abcdefghijklmnopqrstuvwxyz";
    char[] chars = str.toCharArray();
    char[] codes = new char[4];
    Random r = new Random();
    for (int i = 0; i < 4; ++i) {
      int index = r.nextInt(36);
      System.out.println(index);
      codes[i] = chars[index];
    }
    return new String(codes);
  }

  /**
   * 验证码
   * @param response
   * 	
   * @return
   */
  public static String securityCode(HttpServletResponse response) {
    char[] codes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    response.setContentType("image/jpeg");
    BufferedImage image = new BufferedImage(120, 40, 4);
    Random r = new Random();
    Graphics g = image.getGraphics();
    g.setColor(new Color(177, 177, 177));
    g.fillRect(0, 0, 120, 40);
    char[] securityCode = new char[4];
    for (int i = 0; i < 4; ++i) {
      g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
      Font font = new Font("Consolas", 0, 40);
      char c = codes[r.nextInt(10)];
      securityCode[i] = c;
      g.setFont(font);
      g.drawString(new String(new char[] { c }), i * 30, 36);
    }
    OutputStream os = null;
    try {
      os = response.getOutputStream();
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
      encoder.encode(image);
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (os != null)
        try {
          os.flush();
          os.close();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
    }

    return new String(securityCode);
  }

  public static Map<String, Object> fileUpload(HttpServletRequest request) {
    try {
      request.setCharacterEncoding("utf-8");
    } catch (UnsupportedEncodingException e1) {
      throw new RuntimeException(e1);
    }
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Map<String,Object> map = new HashMap<String,Object>();
    if (isMultipart) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      ServletContext servletContext = request.getServletContext();
      File repository = (File)servletContext.getAttribute("javax.servlet.context.tempdir");
      factory.setRepository(repository);
      ServletFileUpload upload = new ServletFileUpload(factory);
      try
      {
        @SuppressWarnings("unchecked")
		List<FileItem> fileItems = upload.parseRequest(request);
        Iterator<FileItem> iterator = fileItems.iterator();
        while (iterator.hasNext()) {
          FileItem fileItem = (FileItem)iterator.next();
          if (fileItem.isFormField())
            map.put(fileItem.getFieldName(), fileItem.getString());
          else
            map.put(fileItem.getFieldName(), fileItem);
        }

      }
      catch (FileUploadException e)
      {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      throw new RuntimeException("上传文件时,isMultipart=false!!!");
    }
    return map;
  }

  public static JSONObject getParameter(ServletRequest request) {
    int i = request.getContentLength();
    byte[] b = new byte[i];
    try {
      ServletInputStream in = request.getInputStream();
      in.read(b);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    String str = new String(b);
    return JSONObject.fromObject(str);
  }
  
//  public static String remoteCall(String url, String postStr, Map<String, String> parameters) {
//    Set ps;
//    try {
//      ps = parameters.entrySet();
//
//      Iterator it = ps.iterator();
//
//      URL u = new URL(url);
//      URLConnection connection = u.openConnection();
//      connection.setDoOutput(true);
//      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
//      while (it.hasNext())
//        connection.addRequestProperty((String)((Map.Entry)it.next()).getKey(), (String)((Map.Entry)it.next()).getValue());
//
//      out.write(postStr);
//      out.flush();
//      out.close();
//      String currentLine = "";
//      String total = "";
//      BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//      while ((currentLine = br.readLine()) != null)
//        total = total + currentLine + "\r\n";
//
//      return total;
//    } catch (Exception e) {
//      throw new RuntimeException(e);
//    }
//  }

  public static String dateFormat(Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return sdf.format(date);
  }

  public static Date dateFormat(String dateStr) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      return sdf.parse(dateStr);
    } catch (ParseException e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
  }

  public static String hanyuToPinyin(String chinese) {
    String pinyin = "";
    char[] nameChar = chinese.toCharArray();
    HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    for (int i = 0; i < nameChar.length; ++i)
      if (nameChar[i] > 19968)
        try {
          pinyin = pinyin + net.sourceforge.pinyin4j.PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
        } catch (Exception e) {
          e.printStackTrace();
        }
      else
        pinyin = pinyin + nameChar[i];


    return pinyin;
  }
}